/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.jflow.db;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;

import com.jeesite.common.tests.BaseInitDataTests;
import com.jeesite.modules.gen.utils.GenUtils;

/**
 * 初始化核心表数据
 * @author ThinkGem
 * @version 2020-5-26
 */
@Component
@ConditionalOnProperty(name="jeesite.initdata", havingValue="true", matchIfMissing=false)
public class InitJflowData extends BaseInitDataTests {

	@Override
	public boolean initData() throws Exception {
		if (GenUtils.isTableExists("wf_flow")) {
			return true; // 如果表已存在，则无需初始化
		}
		
		// JFlow 初始化依赖 Web 环境，所以需要模拟 Web 环境
		MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext)applicationContext).build();
		MockServletContext mockServletContext = (MockServletContext)mockMvc.getDispatcherServlet().getServletContext();
		MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
		RequestContextHolder.setRequestAttributes(servletWebRequest);
		
		// 初始化 JFlow 数据库
		bp.wf.Glo.DoInstallDataBase("CH", 2);
		// 执行  JFlow 数据库升级
		bp.wf.Glo.UpdataCCFlowVer();
		// 给 JFlow 数据表加注释
		bp.sys.PubClass.AddComment();
		
		// 初始化 JFlow 的菜单和视图
		initModuleInfo("jflow");
		initModuleMenu("//WF/Admin/Portal/Default.htm");
		runCreateScript("jflow_view.sql");
		
		return true;
	}
	
}
